package ar.fiuba.tp7552.buildadmin.webactions.users;

import ar.fiuba.tp7552.buildadmin.model.auth.User;
import ar.fiuba.tp7552.buildadmin.model.builds.Edificio;
import ar.fiuba.tp7552.buildadmin.service.PermissionService;
import ar.fiuba.tp7552.buildadmin.service.PermissionType;
import ar.fiuba.tp7552.buildadmin.service.UserService;
import ar.fiuba.tp7552.buildadmin.webactions.BaseAction;

import com.opensymphony.xwork2.Preparable;

public class PermissionAction extends BaseAction implements Preparable {
	
	private UserService userService;
	private PermissionService permService;
	
	private User user = new User();
	private Edificio edificio = new Edificio();
	private String type[];
	
	// ~~ Constructor ====================================================
	
	public PermissionAction(UserService userService, PermissionService permService) {
		super();
		this.userService = userService;
		this.permService = permService;
	}
	
	// ~~ Actions ========================================================
	
	/**
	 * Obtiene de la db el usuario si corresponde.
	 */
	@Override
	public void prepare() {
		if (user != null && user.getId() != null) {
			user = userService.getUser(user.getId());
		}
	}
	
	public String addPermission() {
		
		for (String t : type) {
			PermissionType ptype = PermissionType.valueOf(t);
			permService.addPermission(edificio, user, ptype.getPermission());
		}
		return BaseAction.SUCCESS;		
	}
	
	public String delPermission() {
		for (String t : type) {
			PermissionType ptype = PermissionType.valueOf(t);
			permService.deletePermission(edificio, user, ptype.getPermission());
		}
		return SUCCESS;
	}
	
	// ~~ getters y setters ========================================================

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Edificio getEdificio() {
		return edificio;
	}

	public void setEdificio(Edificio edificio) {
		this.edificio = edificio;
	}

	public String[] getType() {
		return type;
	}

	public void setType(String[] type) {
		this.type = type;
	}	
}
